package com.example.userprofile

import kotlinx.coroutines.flow.Flow
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class UserRepository @Inject constructor(
    private val webservice: UserWebservice,
    private val executor: Executor,
    private val userDao: UserDao
) {
    //without hilt dependency injection
    //private val webservice2: UserWebservice = WebServiceFactory.userWebservice(WebServiceFactory.retrofit(WebServiceFactory.httpClient()));

    fun getUser(userId: String) : Flow<User> {
        refreshUser(userId)
        return userDao.load(userId)
    }

    private fun refreshUser(userId: String){
        val userExists = userDao.hasUser(userId)

        if(!userExists){
            val response = webservice.getUser(userId).execute()

            userDao.save(response.body()!!)
        }
    }


    companion object {
        val FRESH_TIMEOUT = TimeUnit.DAYS.toMillis(1)
    }
}
